
var isInitialPage = 1;

//Populate selection input in form 
function populateApplicationsFormHandler(data){
    console.log('populateApplicationsFormHandler - called');
    console.log(data); 

    if (data != null)
    {
        appDataArray = data;

        for (i = 0; i < data.length; i++) 
        {
            $('#appList')
                .append($("<option></option>")
                    .attr("value", data[i][0])
                    .text(data[i][0]+" - "+ data[i][1]));
        }
        
        currentAppData = appDataArray[0];
        
        //Populate dates
        $.ajax({
            url:		'nabtonData.php',
            dataType:	'json',
            success:	setValidDaysHandler,
            error:		errorHandler("Populate initial failed"),
            type:		'POST',
            data:		{ 
                            action: 'fetchValidDates',
                            appId: data[0][0]
                        }
	    });
    }
}

function setValidDaysHandler(data){
    //console.log('setValidDaysHandler - called');
    //console.log(data); 

    $("#datepicker-1").datepicker( "option", "beforeShowDay", function (date) {
            if($.inArray($.datepicker.formatDate('yy-mm-dd', date), data) > -1)
            {
                return [true];
            }
            else
            {
                return [false];
            }
        } );
    
    var latestDate = new Date(data[data.length-1]);
    $("#datepicker-1").datepicker("setDate", latestDate);
    $("#datepicker-1").datepicker("refresh");
    
     $("#datepicker-2").datepicker( "option", "beforeShowDay", function (date) {
            if($.inArray($.datepicker.formatDate('yy-mm-dd', date), data) > -1)
            {
                return [true];
            }
            else
            {
                return [false];
            }
        } );
    $("#datepicker-2").datepicker("setDate", latestDate);
    $("#datepicker-2").datepicker("refresh");
    
    // Load chart from first available date
    latestDate.setHours(0);
    latestDate.setMinutes(0);
    latestDate.setSeconds(0);
    
    //+ One day
    var toDate = new Date(data[data.length-1]);
    toDate.setHours(23);
    toDate.setMinutes(59);
    toDate.setSeconds(59);
    
    if (isInitialPage == 1)
    {
        isInitialPage = 0;
        //console.log("Loading initial chart for date: " + latestDate);
        loadChart(latestDate,toDate);
    }

}

//#############################################
//# Function - ErrorHandler() 
//# Description: Called when ajax-post fails. Prints error to console
//#############################################
function errorHandler(textStatus)
{
    console.log(textStatus);
}